package com.atguigu.reflect;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;

public class TestCar {
    @Test
    public void test01() throws Exception {
        // 获取class对象多种方式
        Class<Car> clazz1 = Car.class;
        System.out.println(clazz1);
        Class clazz2 = new Car().getClass();
        System.out.println(clazz2);
        Class clazz3 = Class.forName("com.atguigu.reflect.Car");
        System.out.println(clazz3);

        //  实例化
        Car car = (Car) clazz3.getDeclaredConstructor().newInstance();
        System.out.println(car);
    }

    @Test
    public void test02() throws Exception {
        // 获取所有构造器
        Class<Car> clazz1 = Car.class;
        // getConstructors 只能获取public
        // Constructor[] constructors = clazz1.getConstructors();
        // 获取所有
        Constructor[] constructors = clazz1.getDeclaredConstructors();
        for(Constructor c : constructors){
            System.out.println(c.getName()+"-"+c.getParameterCount());
        }

        // ------- 获取单个构造器
        Constructor c1 = clazz1.getConstructor(String.class, Integer.class);
        Car o =(Car) c1.newInstance("奔驰",2);
        System.out.println(o);
    }

    @Test
    public void test03() throws Exception {
        // ------- 获取属性
        Class<Car> clazz = Car.class;
        Car car = (Car) clazz.getDeclaredConstructor().newInstance();
        Field[] fields = clazz.getDeclaredFields();
        for(Field f : fields){
            if(f.getName()=="name") {
                // 设置允许访问
                f.setAccessible(true);
                f.set(car, "华为汽车");
                System.out.println(f.getName() + "---" + car);
            }
        }
    }

    @Test
    public void test04() throws Exception {
        // ----- 获取方法
        Car car = new Car("小米汽车", 10);
        Class clazz = car.getClass();
        Method[] methods = clazz.getMethods();
        for(Method m : methods){
            if(m.getName().equals("toString")){
                String str = (String)m.invoke(car);
                System.out.println("方法调用"+str);
            }
            System.out.println(m.getName()+"---"+m.getParameterCount());
        }
    }
}
